<?php

namespace App\Exceptions;

use App\Trip\Auth\JWT\Exceptions\TokenInvalidException;
use App\Trip\Code;
use App\Trip\Traits\Response as ResponseTrait;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    use ResponseTrait;

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport
        = [
        ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash
        = [
            'current_password',
            'password',
            'password_confirmation',
        ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
//            var_dump($e->getMessage());
        });
    }

    public function report(Throwable $e)
    {
        Log::error('['.$e->getLine().'] "'.$e->getMessage()."-".$e->getFile());
    }

    public function render($request, Throwable $e)
    {
        $code = (int)$e->getCode() ?: 1;
        if ($e instanceof NotFoundHttpException) {
            return $this->error(Code::NOT_FOUND, 'page not found');
        }

        if ($e instanceof TokenInvalidException) {
            return $this->error(Code::UNAUTHORIZED, 'token is invalid');
        }

        // 过滤路径信息
        $msg = $e->getMessage();
        if (App::isLocal()) {
            $msg .= "-".$e->getFile()."-".$e->getLine();
        } else {
            if (Str::contains($msg, "SQL")) {
                $msg = "DB ERROR";
            }

            if (Str::contains($msg, "must not be accessed before initialization")) {
                $msg  = "INNER ERROR";
                $code = 502;
            }

            if (Str::contains($msg, "No query results for model")) {
                $msg  = "data not found";
                $code = 404;
            }
            $msg = Str::replace(base_path(), "", $msg);
        }

        return $this->error($code, $msg);
    }
}
